#encoding=utf-8

import datetime
import time
import urllib
import ujson

from django import forms
from django.contrib import admin
from django.db.models import Count, Max, F, Sum
from django.db.models.query import QuerySet
from django.utils.safestring import mark_safe
from django.utils.html import format_html
from django.contrib.auth.views import login
from django.contrib.auth.models import User,Group
from django.contrib import messages
from andy_manager import settings
import websys.webconfig as webconfig

from websys.models import (
AgentInfo,UserInfo,GameInfo,RoomInfo,WithdrawRecord,AgentBank,
)
import xadmin
from xadmin.views.list import ResultRow, ResultItem
from websys.admin.AdminLoginForm import AdminAuthenticationForm
from xadmin.views import website
from django.contrib.admin import SimpleListFilter
from xadmin.filters import BaseFilter
from django.utils.translation import ugettext_lazy as _

class WithdrawCreationForm(forms.ModelForm):
    mycid = forms.CharField(label=_("Mycid"), widget=forms.HiddenInput)
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'password_mismatch': _("Error,The two password fields didn't match."),
        'add_forbid': _("can not add next agent."),
         'blank_parent': _("parent not blank."),
        'comrate_error': _("comrate not more than %(par)s"),
    }

    applymoney = forms.IntegerField(label=_("提现金额"), widget=forms.TextInput,help_text="提现的金额不能小于"+str(webconfig.MIN_WITHDRAW_MONEY))

    def clean_applymoney(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.

        #周几才能提取
        t_weekday=datetime.datetime.now().weekday()+1
        if t_weekday!=webconfig.WITHDRAW_WEEKDAY:
            raise forms.ValidationError("每周"+str(webconfig.WITHDRAW_WEEKDAY)+"才能申请提取")

        cur_money = self.cleaned_data["applymoney"]
        min_money=webconfig.MIN_WITHDRAW_MONEY

        if cur_money<min_money:#代理登陆进去时添加不能为空
            raise forms.ValidationError('')#提现的金额不能小于"+str(min_money))
        elif int(cur_money)%int(min_money)!=0:
            raise forms.ValidationError("您的提现的金额必须为"+str(min_money)+"的倍数")
        else:
            #print(dir(self))
            login_cid=self.data['mycid']
            ag_info=AgentInfo.objects.get(classid=login_cid)
            max_num=ag_info.lastmoney
            #print('---clean_applymoney---')
            if(cur_money>max_num):
                raise forms.ValidationError("您的最大提现的金额为"+str(max_num))

        return cur_money

class WithdrawRecordAdmin(object):
    #pass
    list_display=('account','applymoney','bankcard','bank','truename','create_time','status_state','oper_column')
    search_fields=('truename','bankcard','account')
    list_filter = ('truename','account')
    fields=('bankid','truename','phone','bankcard','bank','applymoney')
    list_exclude = ("id","agentid")

    def status_state(self, obj):#自定义列
        if obj.status == 0:
            return u'<span style="color:red;font-weight:bold">未发放</span>'
        elif obj.status == -1:
            return u'<span style="color:red;font-weight:bold">已退回</span>'
        elif obj.status == 1:
            return u'<span style="color:green;font-weight:bold">已发放</span>'
        else:
            return u'<span style="color:orange;font-weight:bold">%s</span>' % (u"其它",)
    status_state.short_description = u'状态'
    status_state.allow_tags = True

    def oper_column(self,obj):
        t_html=''
        if obj.status == 0:
            t_html+=u'<button type="button" id="my_status_{0}" class="btn btn-success" autocomplete="off"' \
                   u' onclick="oper_status(\'#my_status_{0}\', \'{0}\', \'{1}\', \'{4}\')">{2}</button>' .format (obj.pk,1,"发放","末操作",obj.account)
            t_html+=u'&nbsp;&nbsp;<button type="button" id="my_status22_{0}" class="btn btn-success" autocomplete="off"' \
                   u' onclick="oper_status(\'#my_status22_{0}\', \'{0}\', \'{1}\', \'{4}\')">{2}</button>' .format (obj.pk,-1,"退回","末操作",obj.account)
        else:
            pass
        return t_html
    oper_column.short_description = u'操作'
    oper_column.allow_tags = True

    def get_list_display(self):
         list_display = super(WithdrawRecordAdmin, self).get_list_display()
         if not self.user.is_superuser and (not self.user.groups.filter(pk=webconfig.ADMIN_AGENT_GROUP_ID).count()==1):
             list_display.remove('oper_column')
         return list_display

    #添加资源
    def get_media(self):
        media = super(WithdrawRecordAdmin, self).get_media()
        media.add_js((self.static('WithdrawAdminAdmin.js'),))
        media.add_js((self.static('ButtonControl.js'),))
        return media

    def formfield_for_dbfield(self, db_field, **kwargs):#重写编辑列显示
        if db_field.get_attname() == "agentid_id":#只获取自己下线
            login_uid = self.user.username
            if AgentInfo.objects.filter(account=login_uid).exists():#是代理
                a_info=AgentInfo.objects.get(account=login_uid)
                kwargs["queryset"] = AgentInfo.objects.filter(account=login_uid)
                #kwargs["queryset"] = AgentInfo.objects.filter(classid__startswith=a_info.classid)#.exclude(account=login_uid)
        if db_field.get_attname() == "bankid_id":#只获取自己下线
            login_uid = self.user.username
            if AgentInfo.objects.filter(account=login_uid).exists():#是代理
                a_info=AgentInfo.objects.get(account=login_uid)
                kwargs["queryset"] = AgentBank.objects.filter(agentid=a_info)
        return super(WithdrawRecordAdmin, self).formfield_for_dbfield(db_field, **kwargs)

    def get_model_form(self, **kwargs):
        if self.org_obj is None:
            self.form = WithdrawCreationForm

        return super(WithdrawRecordAdmin, self).get_model_form(**kwargs)

    def queryset(self):
        queryset_all = super(WithdrawRecordAdmin, self).queryset()
        if not self.user.is_superuser:
            login_uid = self.user.username

            if AgentInfo.objects.filter(account=login_uid).exists():#是代理
                a_info=AgentInfo.objects.get(account=login_uid)
                qs = queryset_all.filter(agentid_id=a_info.id)

                return qs

        return queryset_all

    def save_models(self):#重写保存操作
        obj = self.new_obj
        #是新增获取当前登陆的代理信息
        if (self.org_obj is None):
            tuser=self.user.username
            ag_info=AgentInfo.objects.get(account=tuser)
            # #判断是否够
            # min_num=100
            # max_num=ag_info.lastmoney
            cur_num=obj.applymoney
            # if(cur_num<min_num ):
            #     raise Exception("提现的金额不能小于"+str(min_num))
            # if(cur_num>max_num ):
            #     raise Exception("您的最大提现的金额为"+str(max_num))

            obj.agentid=ag_info
            obj.account=ag_info.account
            obj.save()
            #扣代理的钱
            ag_info.lastmoney-=cur_num
            ag_info.save()

xadmin.site.register(WithdrawRecord, WithdrawRecordAdmin)
